/**
 * Created by hjqi on 2016/3/3.
 */
module.controller('StorageCreateModalController',
    function ($scope,$cookies,$stateParams,$mdDialog,storageService) {

        $scope.nameReg = '[a-z0-9]([-a-z0-9]*[a-z0-9])?';
        $scope._lock = false;
        $scope.disabled1=512;
        $scope.ok = function(evt){
            disabledButton();
            if($scope.form.$valid){
                if($scope.storageId !== undefined && $scope.storageId !== "" && $scope._lock === false){
                    $scope._lock = true;
                    var date=new Date();
                    storageService.createStorage($scope.storageId,$scope.disabled1,date).then(function(r){
                            if(r.data.ret == true){
                                alertify.success("create storage"+$scope.storageId+" success");
                                //after create success , it could refresh storage list
                                $scope._lock = false;
                                $mdDialog.hide(r.data.data);
                            }else{
                                $scope._lock = false;
                                alertify.error(r.data.data);
                            }
                        },
                        function(err){
                            $scope._lock = false;
                            if(err.data.data == undefined){
                                alertify.error("create storage error:"+err.data.data);
                            } else {
                                alertify.error("Something bad happen:"+err.data.error);
                            }
                        }
                    );
                }
            }
            // The countdown to enabledButton again
            setTimeout(function(){
                enabledButton()
            },3000);
        };
        $scope.cancel=function(){
            $mdDialog.cancel();
        };

        // can't click the button again in the next 3 seconds
        function disabledButton(){
            var inputs = document.getElementsByName("Storage_OK");
            for(var i = 0;i<inputs.length;i++){
                if(inputs[i].type.toLowerCase()=="button")
                    inputs[i].disabled=true;
            }
        }

        function enabledButton(){
            var inputs = document.getElementsByName("Storage_OK");
            for(var i = 0;i<inputs.length;i++){
                if(inputs[i].type.toLowerCase()=="button")
                    inputs[i].disabled=false;
            }
        }

    }
);